<template>
<div>
    <div class="search">
     <input v-model="keyword" class="search-input" classtype="text" placeholder="输入城市名或拼音" /> 
    </div>
    <div class="search-content" 
      v-show="keyword"
      ref="search">
        <ul>
            <li class="search-item border-bottom" 
            v-for="item of list" 
            :key="item.id"
             @click="handleCityClick(item.name)"
            >{{item.name}}</li>
            <li class="search-item border-bottom" v-show="hasNoData">没有找到匹配数据</li>
        </ul>
    </div>
</div>
</template>
<script>
import Bscroll from 'better-scroll'
import {mapMutations} from 'vuex'
export default {
    name: "citySearch",
    props:{
        cities:Object
    },
    data () {
        return{
     keyword:'',
     list : [],
     timer : null
        }
    
    },
    watch:{
        keyword () {//监听搜索框里输入的值，以下运用事件节流（面试会问：防抖）
            if(this.timer){
             clearTimeout(this.timer)
            }
            if(!this.keyword){
             this.list = [];
             return
            }
            this.timer=setTimeout(() => {
            const result = []
            for (let i in this.cities){//对cities进行循环
             this.cities[i].forEach((value) => {//遍历每个字母项
                 if(value.spell.indexOf(this.keyword) > -1||//如果搜索框输入的字母在cities[i]中存在
                   value.name.indexOf(this.keyword) > -1 ){
                   result.push(value)
                 }
             });
            }
            this.list = result
            },100)
        }
    },
    mounted () {
     this.scroll = new Bscroll(this.$refs.search,{
         click:true//better-scroll会覆盖click事件
     })//使用better-scroll让搜索出来列表可以拖动
    },
    computed:{
        hasNoData () {
        return !this.list.length
        }
    },
    methods: {
    handleCityClick :function(city) {
    //this.$store.dispatch('changeCity',city)//触发一个changeCity的一个action
    //this.$store.commit('changeCity',city)//或者直接略过action也是可以的
     this.changeCity(city)
     this.$router.push('/')
    },
     ...mapMutations(['changeCity'])
    },

};
</script>
<style lang="stylus" scoped>
@import '~styles/variable.styl'
 .search
   height .72rem
   padding 0 .1rem
   background $bgcolor
   .search-input
     box-sizing border-box
     width 100%
     height .62rem
     line-height .62rem
     text-align center
     border-radius:.06rem
     color #666
     padding 0 .1rem
 .search-content
    overflow hidden
    z-index 1
    position  absolute
    background #eee
    top 1.58rem
    left 0
    right 0
    bottom 0
    .search-item
     line-height .62rem
     padding-left .2rem
     color #666
     background #fff

</style>
